package com.cti.commons.delayqueue.core.mode;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneId;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author et.wang
 * @description: 延时任务消息主体
 * @date 2022/10/27 19:33
 */
@Data
@ToString
@NoArgsConstructor
public class DelayMessage<T> implements Serializable {

    private static final long serialVersionUID = -4011638005718462475L;

    /**
     * 延迟任务的唯一标识，用于检索任务
     */
    @JsonSerialize(using = ToStringSerializer.class)
    private long id;

    /**
     * 消息主题
     */
    private String topic;

    /**
     * 任务的执行时间
     */
    private long delayTime;

    /**
     * 任务的执行超时时间
     */
    private long ttrTime;

    /**
     * 任务具体的消息内容，用于处理具体业务逻辑用
     */
    private T body;

    public DelayMessage(long id, String topic, long delayTime, T body) {
        if (id <= 0 || StrUtil.isEmpty(topic) || ObjectUtil.isEmpty(body)) {
            throw new IllegalArgumentException("参数异常");
        }
        this.id = id;
        this.topic = topic;
        this.delayTime = delayTime;
        this.body = body;
    }

    public DelayMessage(String topic, T body, int second) {
        if (StrUtil.isEmpty(topic) || ObjectUtil.isEmpty(body) || second <= 0) {
            throw new IllegalArgumentException("参数异常");
        }
        this.id = IdUtil.getSnowflake().nextId();
        this.topic = topic;
        this.delayTime = plusTime(second);
        this.body = body;
    }

    /**
     * 获取未来的一个时间点
     *
     * @param second
     * @return
     */
    public static Long plusTime(int second) {
        return LocalDateTime.now().plusSeconds(second).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

}
